/**
 * author:Administrator
 * date:2016/3/19
 * desc:TODO
 */

'use strict';
let debug = console.log.bind(console);

class PubSub {
  constructor() {
    this.sub = {};
  }

  /**
   * @param sagaId event flow sagaId
   * @param type event type
   * @param handler event handler
   */
  subscribe(sagaId, type, handler) {
    //console.log('subscribe ', type);
    this.sub[sagaId] = this.sub[sagaId] || {};
    this.sub[sagaId][type] = handler;
  }

  /**
   * @param event
   */
  publish(event) {
    if (!event) return;
    debug('publish ', event);
    let self = this;
    process.nextTick(function () {
      let handler = self.sub[event.sagaId][event.type];
      handler(event);
    });
  }

  unSubscribe(sagaId) {
    delete this.sub[sagaId];
  }
}

let ins = new PubSub();
module.exports = ins;